//
//  LBWHomeTableViewController.swift
//  weibo
//
//  Created by Limonwei on 15/12/5.
//  Copyright © 2015年 heima. All rights reserved.
//

//首页控制器界面

import UIKit
import SVProgressHUD

//cell的可重用标示符
private let LBWStatusCellID = "CELL"

class LBWHomeTableViewController: LBWVisitorTableViewController {
    
    //首页微博数据的视图模型
    var statusListViewModel: LBWStatusListViewModel = LBWStatusListViewModel()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        //未登录访客视图
        if !userLogin {
            
            visitorView?.setVisitorInto(nil, message: nil)
            
            return
        }
        
        setupUI()
        //刷新
        loadData()
    }
    
    //登陆后的视图UI
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: "friendsearch")
        
        
        //设置tableView
        setupTableView()
    }
    
    //Item点击事件
    @objc private func friendsearch(){
        let vc = LBWTempViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func setupTableView() {
        
        //注册cell
        tableView.registerClass(LBWStatusCell.self, forCellReuseIdentifier: LBWStatusCellID)
        
        //设置cell的高度  设置自动计算行高,根据contentView的底部的最大y值去设置成行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //设置预估高度
        tableView.estimatedRowHeight = 200
        
        //隐藏分割线
        tableView.separatorStyle = .None
        
        //设置上拉加载的控件
        tableView.tableFooterView = pullUpView
        
        lbwRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        tableView.addSubview(lbwRefreshControl)
        
        
    }
    
    //懒加载控件
    //上拉加载视图控件 添加一朵菊花
    private lazy var pullUpView: UIActivityIndicatorView = {
       
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view.color = UIColor.redColor()
        
        view.sizeToFit()
        
        return view
        
    }()
    //下拉刷新控件
    private var lbwRefreshControl: LBWRefreshControl = LBWRefreshControl()
    
    //下拉刷新的提示控件
    private lazy var pullDownTipLabel: UILabel = {
    
        let label = UILabel()
        
        label.backgroundColor = UIColor.orangeColor()
        
        label.textColor = UIColor.whiteColor()
        
        label.font = UIFont.systemFontOfSize(12)
        
        label.textAlignment = .Center
        
        //设置默认隐藏
        label.hidden = true
        
        var frame = label.frame
        frame.size = CGSizeMake(SCREENW,35)
        frame.origin.y = 64 - 35
        
        label.frame = frame
        
        //添加控件
        return label
    
    }()

}

//加载数据
extension LBWHomeTableViewController {
    
    //加载微博数据
     @objc private func loadData() {
        
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess, count) -> () in
            if isSuccess {
                self.tableView.reloadData()
                
                if !self.pullUpView.isAnimating(){
                    
                    self.showPullDownTips(count)
                }
            }else{
                SVProgressHUD.showErrorWithStatus("请求失败")
            }
            
            self.endLoad()
        }
        
    }
    //结束刷新
    private func endLoad(){
        
        pullUpView.stopAnimating()
        
        lbwRefreshControl.endRefreshing()
    }
    
    //显示下拉刷新的设置
    private func showPullDownTips(count: Int){
        
        if self.pullDownTipLabel.hidden == false {
            
            return
        }
        //判断当前控件是否被添加到指定位置
        if self.pullDownTipLabel.superview == nil {
            
            if let navCtrl = self.navigationController {
                
                navCtrl.view.insertSubview(self.pullDownTipLabel, belowSubview: navCtrl.navigationBar)
            }
        }
        if count == 0 {
            self.pullDownTipLabel.text = "没有微博数据"
        }else{
            self.pullDownTipLabel.text = "加载了\(count)条数据"
        }
        
        //执行动画
        pullDownTipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, self.pullDownTipLabel.frame.height)
            }) { (_) -> Void in
                
                // 停留一秒再执行另外 的一个动画
                
                UIView.animateKeyframesWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.pullDownTipLabel.hidden = true
                })
        
    }
    
}
}
//tableView delegate & dataSource
extension LBWHomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(LBWStatusCellID, forIndexPath: indexPath) as! LBWStatusCell
        
        //设置数据
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        
        return cell
    }
    
    //将要显示某一个cell的时候调用这个方法
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //如果当前正在加载更多,就不需要再次进入
        if !pullUpView.isAnimating() && indexPath.row == statusListViewModel.statusList!.count - 1 {
            
            pullUpView.startAnimating()
            
            loadData()
        }
    }
    
}























